package com.web.cms.doc.util;

import com.blue.core.dict.State;
import com.web.cms.doc.cache.ChannelCache;
import com.web.cms.doc.model.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("cmsChannelUtil")
public class ChannelUtil
{
	@Autowired
	private ChannelCache channelCache;
	
	public ChannelUtil()
	{
	}
	
	public Channel get(Integer id)
	{
		return channelCache.get(id);
	}
	
	public Map<Integer, List<Channel>> listByWeb(Integer webId, State state)
	{
		//state = (state == null ? State.NORMAL : state);
		Map<Integer, List<Channel>> webMap = channelCache.listByWeb(webId);
		if (webMap == null || webMap.isEmpty())
			return null;
		
		if (state == null)
			return webMap;
		
		Map<Integer, List<Channel>> map = new HashMap<>();
		for (Map.Entry<Integer, List<Channel>> entry : webMap.entrySet())
		{
			List<Channel> list = new ArrayList<>();
			for (Channel channel : entry.getValue())
			{
				if (channel.getState() != null && channel.getState() == state)
				{
					list.add(channel);
				}
			}
			map.put(entry.getKey(), list);
		}
		return map;
	}
	
	public List<Channel> listByWebAndParent(Integer webId, Integer parentId, State state)
	{
		//state = (state == null ? State.NORMAL : state);
		List<Channel> parentList = channelCache.listByWebAndParent(webId, parentId);
		if (parentList == null || parentList.isEmpty())
			return null;
		
		if (state == null)
			return parentList;
		
		List<Channel> list = new ArrayList<>();
		for (Channel channel : parentList)
		{
			if (channel.getState() != null && channel.getState() == state)
			{
				list.add(channel);
			}
		}
		return list;
	}
	
}
